#include "Ast.h"
#include <iostream>

using namespace std;

Ast::Ast(std::string ip, int port) : Agent(ip, port)
{
}

Ast::~Ast()
{
  sendProto("AST/LOGOUT");
}

void Ast::start()
{
  char c;
  string buf, login, EtuID;

    cout<<"Votre LOGIN :"<<endl;		
    getline(cin, login);
    cout<<"LOGIN de l'ETU:"<<endl;
    getline(cin, EtuID);
    int size = login.size();
    int sizeEtuID = EtuID.size();
    
    sendProto("AST/LOGIN");
    sendInt(size);
    sendString(login.c_str(), size);
    sendInt(sizeEtuID);
    sendString(EtuID.c_str(), sizeEtuID);
    
    etulogin = EtuID;
    
    buf = getProto();

	if(buf != "AST/OK/LOGIN")
	{
		cout << "Erreur : le login est invalide ou l'étudiant n'existe pas" << endl;
		return;
	}
  
  cout << "Connection OK" << endl;

  pthread_create(&ecrire, NULL, gere_ecrire, (void*)(this));
  pthread_create(&lire, NULL, gere_lire, (void*)(this));
  pthread_join(ecrire, NULL);
  pthread_cancel(lire);
}

void *Ast::gere_lire(void * arg)
{
	Ast *a = (Ast*)arg;
	int status = 1;
	long size = 0;
	string buf = "";
	
	while(status > 0)
	{
		buf = a->getProto();
		if(buf == "ETUD/MSG")
		{
			size = a->getInt();
			buf = a->getString(size);
			cout << buf << endl;
		}
	}
}

void *Ast::gere_ecrire(void * arg)
{
	//////////////////
	/////MUTEX POUR SAVOIR SI LETU A DECO 
	//////////////////
	Ast * a = (Ast*)arg;
	string line = "";
	
	while(line != "exit")
	{
		cout << "A " << a->etulogin << " : ";
		getline(cin, line);
		if(line != "exit")
		{
			a->sendProto("AST/ETU/MSG");
			a->sendInt(line.size());
			a->sendString(line.c_str(), line.size());
		}
	}
	return NULL;
}
